package test;

import java.util.Scanner;

public class Five {
    public static void main(String[] args) {
        Scanner scanner = new Scanner(System.in);

        System.out.print("请输入目录个数和待查询的目录ID：");
        int m = scanner.nextInt();
        int n = scanner.nextInt();

        int[] sizes = new int[m + 1]; // 存储每个目录的大小
        int[] arr = new int[n + 1]; // 存储每个目录的子目录列表

        // 读取目录信息
        for (int i = 1; i <= m; i++) {
            System.out.print("请输入目录 " + i + " 的大小和子目录列表（用空格分隔）：");
            sizes[i] = scanner.nextInt();
            arr[i] = scanner.nextInt();
        }

        int totalSize = jisuan(sizes, arr, n);
        System.out.println("目录 " + n + " 及其子目录的大小之和为：" + totalSize);
    }

    private static int jisuan(int[] sizes, int[] arr, int directoryId) {
        int totalSize = sizes[directoryId];

        if (arr[directoryId] != 0) {
            String subDirectoryList = String.valueOf(arr[directoryId]);
            String[] strs = subDirectoryList.split("");

            for (String subDirId : strs) {
                totalSize += jisuan(sizes, arr, Integer.parseInt(subDirId));
            }
        }

        return totalSize;
    }
}
